package com.jwdf.uda.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.jwdf.uda.R;

public class FittedLayout extends FrameLayout {

    public static final int MODE_WIDTH = 0x1;
    public static final int MODE_HEIGHT = 0x2;
    private float mRatio = 1;
    private int mMode = MODE_WIDTH;

    public FittedLayout(Context context) {
        super(context);
    }

    public FittedLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.FittedLayout);
        try {
            mRatio = a.getFloat(R.styleable.FittedLayout_layout_ratio, 1);
            mMode = a.getInteger(R.styleable.FittedLayout_layout_mode, MODE_WIDTH);
        } finally {
            a.recycle();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
        int childWidthSize;
        int childHeightSize;
        if (mMode == MODE_WIDTH) {
            childWidthSize = getMeasuredWidth();
            childHeightSize = (int) (childWidthSize * mRatio);
        } else if (mMode == MODE_HEIGHT) {
            childHeightSize = getMeasuredHeight();
            childWidthSize = (int) (childHeightSize * mRatio);
        } else {
            childWidthSize = getMeasuredWidth();
            childHeightSize = getMeasuredHeight();
        }
        widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(childHeightSize, MeasureSpec.EXACTLY);
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

}
